package com.sxt.jt808.server;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sxt.jt808.codec.JT808Decoder;
//import com.sxt.jt808.codec.JT808Encoder;
import com.sxt.jt808.commons.JT808Const;
import com.sxt.jt808.handler.IOHandler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;


/**
 * @Author: 罗林
 * @Date: 2019-05-15
 * @Description:
 * @Version: 1.0
 */
@Component
public class JT808ChannelInitializer extends ChannelInitializer<SocketChannel> {
	
	@Value("${netty.read-timeout}")
    private int readTimeOut;
	
	
	private EventExecutorGroup businessGroup = new DefaultEventExecutorGroup(2);//业务线程池
	
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(
                new IdleStateHandler(readTimeOut, 0, 0, TimeUnit.MINUTES));
        // jt808协议 包头最大长度16+ 包体最大长度1023+分隔符2+转义字符，最大估算60 = 1100
        pipeline.addLast(
                new DelimiterBasedFrameDecoder(1100, Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER}),
                        Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER, JT808Const.PKG_DELIMITER})));
        pipeline.addLast(new JT808Decoder());//解码器
//        pipeline.addLast(new JT808Encoder());//编码器
        pipeline.addLast(businessGroup, new IOHandler());//因为locationMsg中涉及到数据库操作，所以放入businessGroup
	}

}
